#include "skinmanager.h"
#include "fileutils.h"       // 依赖 utils 模块的文件操作
#include "configmanager.h"   // 依赖 core 模块的配置管理

#include <QDebug>
#include <QDir>
#include <QWidget>

SkinManager *SkinManager::instance()
{
	static SkinManager s_instance;
    return &s_instance;
}

void SkinManager::loadSkin(const QString &skinName)
{
	// check 
	QString qssPath;
	if (skinName == "custom") {
		// 自定义皮肤 : from config
		qssPath = ConfigManager::getInstance()->getValue(AppearanceGroup, "CustomSkinPath").toString();
		if (qssPath.isEmpty() || !QFile::exists(qssPath)) {
			qWarning() << "[SkinManager] 自定义皮肤路径无效，加载默认皮肤";
            loadSkin(m_defaultSkin);
            return;
		}
	} else if (m_builtinSkins.contains(skinName)) {
		qssPath = m_builtinSkins[skinName];		// 内置皮肤：使用预定义路径
	} else {
		// 未知 默认皮肤
		qWarning() << "[SkinManager] 未知皮肤：" << skinName << "，加载默认皮肤";
        loadSkin(m_defaultSkin);
        return;
	}

	// qss load
	QByteArray qssContent = loadQssFile(qssPath);
	if (qssContent.isEmpty()) {
		qWarning() << "[SkinManager] QSS文件加载失败：" << qssPath;
        loadSkin(m_defaultSkin);
        return;
	}
	// 全局 apply
	applyGlobalStyle(QString(qssContent));
	m_currentSkin = skinName;

	// save appreance config should aysnc
	AppearanceConfig::Data appearanceConfig = ConfigManager::getInstance()->getAppearanceConfig();
	appearanceConfig.skin = skinName;
	ConfigManager::getInstance()->setAppearanceConfig(appearanceConfig);

	// send singals
	emit skinSwitched(skinName);
    qDebug() << "[SkinManager] 皮肤加载成功：" << skinName << "（路径：" << qssPath << "）";
}

bool SkinManager::importCustomSkin(const QString &qssFilePath)
{
	// check file 
	QString crossPath = FileUtils::getCrossPlatformPath(qssFilePath);
	if (!FileUtils::checkFilePermission(crossPath, true, false)) {
		qWarning() << "[SkinManager] 自定义皮肤文件无读权限：" << crossPath;
        return false;
	}
	if (QFileInfo(crossPath).suffix().toLower() != "qss") {
		qWarning() << "[SkinManager] 无效文件格式，仅支持 .qss 文件：" << crossPath;
        return false;
	}

	// load apply qss
	QByteArray qssContent = loadQssFile(crossPath);
	if (qssContent.isEmpty()) {
		qWarning() << "[SkinManager] 自定义QSS文件加载失败：" << crossPath;
        return false;
	}
	applyGlobalStyle(QString(qssContent));

	// update save config
	m_currentSkin = "custom";
	ConfigManager::getInstance()->setValue(AppearanceGroup, "CustomSkinPath", crossPath);
	AppearanceConfig::Data appearanceConfig = ConfigManager::getInstance()->getAppearanceConfig();
    appearanceConfig.skin = "custom";
    ConfigManager::getInstance()->setAppearanceConfig(appearanceConfig);

	// send change signal
	emit skinSwitched("custom");
    qDebug() << "[SkinManager] 自定义皮肤导入成功：" << crossPath;
    return true;
}

SkinManager::SkinManager(QObject *parent)
    : QObject(parent)
    , m_currentSkin(m_defaultSkin)
{
	// default path
	m_builtinSkins = {
        {"default", ":/resources/skins/default.qss"},
        {"dark", ":/resources/skins/dark.qss"},
        {"simple", ":/resources/skins/simple.qss"}
    };
	// 上次使用的皮肤 （>=default）
	QString savedSkin = ConfigManager::getInstance()->getAppearanceConfig().skin;
    if (!savedSkin.isEmpty() && (m_builtinSkins.contains(savedSkin) || savedSkin == "custom")) {
        m_currentSkin = savedSkin;
        loadSkin(m_currentSkin);  // 启动时自动加载配置的皮肤
    } else loadSkin(m_defaultSkin);  // 配置无效时加载默认皮肤
}

QByteArray SkinManager::loadQssFile(const QString &qssPath)
{
	// utils的模块依赖
	return FileUtils::readEncryptedFile(qssPath, FileUtils::NoEncrypt);
}

void SkinManager::applyGlobalStyle(const QString &qssContent)
{
	// apply all --> whole QWidget 
	qApp->setStyleSheet(qssContent);

	// sameway the window
	int transparency = ConfigManager::getInstance()->getAppearanceConfig().windowTransparency;
	QList<QWidget*> topLevelWidgets = qApp->topLevelWidgets();
	for (auto* widget : topLevelWidgets) {
		// 主窗口
		if (widget->isWindow() && !widget->inherits("QDialog"))	widget->setWindowOpacity(transparency / 100.0);
	}
}
